package org.qiqi.edu.controller.system;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.qiqi.edu.common.QiQiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author qiqiang
 * @date 2019-02-15
 */
@RestController
@Slf4j
public class WeChatController {

    @Value("${wechat.secret}")
    private String secret;
    @Value("${wechat.appid}")
    private String appid;

    private static final String URL = "https://api.weixin.qq.com/sns/jscode2session?" +
            "appid={appid}&secret={secret}&js_code={js_code}&grant_type=authorization_code";

    private final RestTemplate restTemplate;

    @Autowired
    public WeChatController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @PostMapping("/openId")
    public QiQiResponse openId(String code) {
        String openid = "";
        Map<String, String> uriVariable = new HashMap<>(4);
        uriVariable.put("appid", appid);
        uriVariable.put("secret", secret);
        uriVariable.put("js_code", code);
        uriVariable.put("grant_type", "authorization_code");
        ResponseEntity<JSONObject> response = restTemplate.getForEntity(URL, JSONObject.class, uriVariable);
        if (HttpStatus.OK.equals(response.getStatusCode())) {
            log.info("receive response body is : {}", JSONObject.toJSON(response.getBody()));
            openid = response.getBody().getString("openid");
        }
        return QiQiResponse.ok("ok", openid);
    }
}
